package com.test.reggie.model.address;

import android.app.Activity;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;

import com.lxj.xpopup.XPopup;
import com.test.reggie.R;
import com.test.reggie.base.BaseActivity;
import com.test.reggie.base.BaseRVAdapter;
import com.test.reggie.base.BaseRVHolder;
import com.test.reggie.bean.AddAddressBean;
import com.test.reggie.bean.AddressBookListBean;
import com.test.reggie.bean.State;
import com.test.reggie.bean.StringBean;
import com.test.reggie.bean.UserBean;
import com.test.reggie.databinding.ActivityAddressBinding;
import com.test.reggie.http.API;
import com.yechaoa.yutils.GsonUtil;
import com.yechaoa.yutils.ToastUtil;
import com.yechaoa.yutils.YUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 地址管理
 */
public class AddressActivity extends BaseActivity<ActivityAddressBinding, AddressPrensenter> implements
        AddressView, View.OnClickListener {

    private UserBean userBean;
    private BaseRVAdapter<AddressBookListBean.DataBean> adapter;
    private int pos;
    private int ADD = 201;
    private int UPDATE = 202;
    private String type;

    @Override
    protected AddressPrensenter createPresenter() {
        return new AddressPrensenter(this);
    }

    @Override
    protected void initView() {
        viewBinding.ic.tvTitle.setText("地址管理");
        viewBinding.ic.llBack.setOnClickListener(this);
        viewBinding.btnAddAddress.setOnClickListener(this);

        userBean = GsonUtil.GsonToBean(String.valueOf(API.kv.decodeString(State.user)),
                UserBean.class);

        type = getIntent().getStringExtra("type");
    }

    @Override
    protected void initData() {
        YUtils.showLoading("加载中...");
        presenter.addressBookList(userBean.getData().getId());//查询指定用户的全部地址
        adapter = new BaseRVAdapter<AddressBookListBean.DataBean>(R.layout.item_address) {
            @Override
            public void onBindVH(BaseRVHolder holder, AddressBookListBean.DataBean data, int position) {
                TextView tv_lable = holder.getView(R.id.tv_lable);
                TextView tv_sex = holder.getView(R.id.tv_sex);
                RadioButton rb_isDefault = holder.getView(R.id.rb_isDefault);
                ImageView iv_edit = holder.getView(R.id.iv_edit);
                TextView tv_delete = holder.getView(R.id.tv_delete);
                LinearLayout ll_cotent = holder.getView(R.id.ll_cotent);

                if (data.getLabel() == 0) {
                    tv_lable.setText("无");
                } else if (data.getLabel() == 1) {
                    tv_lable.setText("公司");
                } else if (data.getLabel() == 2) {
                    tv_lable.setText("家");
                } else if (data.getLabel() == 3) {
                    tv_lable.setText("学校");
                }
                holder.setText(R.id.tv_detail, data.getDetail());
                holder.setText(R.id.tv_name, data.getConsignee());
                if (data.getSex() == 1) {
                    tv_sex.setText("先生");
                } else if (data.getSex() == 2) {
                    tv_sex.setText("女士");
                }
                holder.setText(R.id.tv_phone, data.getPhone());
                if (data.getIsDefault() == 0) {
                    rb_isDefault.setChecked(false);
                } else if (data.getIsDefault() == 1) {
                    rb_isDefault.setChecked(true);
                }

                rb_isDefault.setOnCheckedChangeListener((buttonView, isChecked) -> {//设置默认地址
                    if (isChecked) {
                        new XPopup.Builder(AddressActivity.this).asConfirm("提示",
                                "确定设为默认地址吗",
                                () -> {
                                    pos = position;
                                    YUtils.showLoading("提交中...");
                                    Map<String, Object> mapSetDefault = new HashMap<>();
                                    mapSetDefault.put("id", data.getId());//id
                                    mapSetDefault.put("userId", data.getUserId());//用户id
                                    presenter.setDefault(mapSetDefault);//设置默认地址
                                },
                                () -> {
                                    rb_isDefault.setChecked(false);
                                }).show();
                    }
                });

                iv_edit.setOnClickListener(v -> {//编辑
                    pos = position;
                    Intent intent = new Intent(AddressActivity.this, AddAddressActivity.class);
                    intent.putExtra("id", data.getId());
                    startActivityForResult(intent, UPDATE);
                });

                tv_delete.setOnClickListener(v -> {//删除
                    new XPopup.Builder(AddressActivity.this).asConfirm("提示",
                            "确定删除该地址吗",
                            () -> {
                                pos = position;

                                YUtils.showLoading("提交中...");
                                presenter.deleteAddressBook(data.getId());//删除地址
                            }).show();
                });

                if (type != null && "jiesuan".equals(type)) {
                    ll_cotent.setOnClickListener(v -> {
                        Intent intent = new Intent();
                        intent.putExtra("data", data);
                        setResult(Activity.RESULT_OK, intent);
                        finish();
                    });
                }
            }
        };

        empty("暂无数据");

        viewBinding.rv.setAdapter(adapter);
        viewBinding.rv.setLayoutManager(new GridLayoutManager(this, 1));//列数设置
    }

    private void empty(String msg) {
        View empty = LayoutInflater.from(this).inflate(R.layout.layout_no_data, null, false);
        TextView tv_tip = empty.findViewById(R.id.tv_tip);
        tv_tip.setText(msg);
        adapter.setEmptyView(empty);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ADD && resultCode == Activity.RESULT_OK) {
            presenter.addressBookList(userBean.getData().getId());//查询指定用户的全部地址
        } else if (requestCode == UPDATE && resultCode == Activity.RESULT_OK) {
            String name = data.getStringExtra("name");
            int sex = data.getIntExtra("sex", 0);
            String phone = data.getStringExtra("phone");
            String address = data.getStringExtra("address");
            int tag = data.getIntExtra("tag", 0);
            adapter.getData().get(pos).setConsignee(name);
            adapter.getData().get(pos).setSex(sex);
            adapter.getData().get(pos).setPhone(phone);
            adapter.getData().get(pos).setDetail(address);
            adapter.getData().get(pos).setLabel(tag);
            adapter.notifyItemChanged(pos);
        }
    }

    @Override
    public void addressBookListSuccess(AddressBookListBean bean) {
        YUtils.hideLoading();
        if (bean.getCode() == 200) {
            adapter.setNewData(bean.getData());
        } else {
            ToastUtil.showCenter(bean.getMsg());
        }
    }

    @Override
    public void onError(String msg) {
        YUtils.hideLoading();
        ToastUtil.showCenter(msg);
    }

    @Override
    public void setDefaultSuccess(AddAddressBean bean) {
        YUtils.hideLoading();
        ToastUtil.showCenter(bean.getMsg());
        if (bean.getCode() == 200) {
            presenter.addressBookList(userBean.getData().getId());//查询指定用户的全部地址
        }
    }

    @Override
    public void deleteAddressBookSuccess(StringBean bean) {
        YUtils.hideLoading();
        ToastUtil.showCenter(bean.getMsg());
        if (bean.getCode() == 200) {
            adapter.remove(pos);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_add_address://添加收货地址
                Intent intent = new Intent(AddressActivity.this, AddAddressActivity.class);
                startActivityForResult(intent, ADD);
                break;
            case R.id.ll_back:
                finish();
                break;
            default:
                break;
        }
    }
}